package cn.cellcom.agent.struts.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.common.AgentEnv;
import cn.cellcom.agent.hql.TWorderHql;
import cn.cellcom.agent.pojo.TCrm;
import cn.cellcom.agent.pojo.TSession;
import cn.cellcom.agent.pojo.TWorder;
import cn.cellcom.agent.struts.form.TWorderForm;
import cn.cellcom.agent.util.RedisManager;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.dao.IBaseDao;
import cn.cellcom.jar.env.Env;
import cn.cellcom.jar.file.FU;
import cn.cellcom.jar.file.FileLoad;
import cn.cellcom.jar.file.FileProcessor;
import cn.cellcom.jar.file.IFileLoad;
import cn.cellcom.jar.file.IFileProcessor;
import cn.cellcom.jar.logon.LogonSession;
import cn.cellcom.jar.pagination.AbstractPaginationBiz;
import cn.cellcom.jar.pagination.IPaginationBiz;
import cn.cellcom.jar.port.ExportTemplate;
import cn.cellcom.jar.port.IDataPort;
import cn.cellcom.jar.port.ImportTemplate;
import cn.cellcom.jar.port.JxlPort;
import cn.cellcom.jar.util.BeanUtil;
import cn.cellcom.jar.util.CU;
import cn.cellcom.jar.util.ConversionUtils;
import cn.cellcom.jar.util.DT;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MyException;

public class TWorderDpAct extends DispatchAction {

	private IPaginationBiz pbiz;

	private AbstractBiz cbiz;

	private Log log = LogFactory.getLog(this.getClass());

	/**
	 * 查询记录
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		form = (ActionForm) AbstractPaginationBiz.getPaginationActionForm(req, form);
		List list = null;
		try {
			log.info("查询的语句：TWorderHql()");
			list = pbiz.pagination(mapping, form, req, new TWorderHql()).getDataResult();

			req.setAttribute(Env.DATA_NAME, list);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "操作出现错误", e, mapping, req);
		}
		req.setAttribute("statuslist", BeanUtil.startWith("TWorder-status"));
		req.setAttribute("levellist", BeanUtil.startWith("TWorder-level"));
		req.setAttribute("createSourcelist", BeanUtil.startWith("TWorder-createSource"));

		return mapping.findForward("list");
	}

	/**
	 * 准备记录添加
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		req.setAttribute("statuslist", BeanUtil.startWith("TWorder-status"));
		req.setAttribute("levellist", BeanUtil.startWith("TWorder-level"));
		req.setAttribute("createSourcelist", BeanUtil.startWith("TWorder-createSource"));

		String cid = req.getParameter("cid");
		String sid = req.getParameter("sid");
		try {
			TCrm crm = (TCrm) cbiz.getDao().myGet(TCrm.class, cid);
			TSession session = (TSession) cbiz.getDao().myGet(TSession.class, sid);
			req.setAttribute("crm", crm);
			req.setAttribute("session", session);
			req.setAttribute("subject", "这是IM会话创建的工单");
		} catch (MyException e) {
			LogUtil.e(this.clazz, "", e);
		}

		return mapping.findForward("add");
	}

	/**
	 * 执行记录添加
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TWorderForm fm = (TWorderForm) form;
		Object obj = null;
		try {
			obj = cbiz.add(req, fm, null);
		} catch (MyException e) {
			LogUtil.e(this.clazz, "新增数据出现异常", e);
		}
		log.info("新增记录结果：" + obj);
		String message;
		if (obj == null || !(obj instanceof TWorder)) {
			req.setAttribute(Env.DATA_NAME, "操作失败，" + obj);
			return mapping.findForward("error");
		} else {
			message = "工单发起成功，可以继续发起";
		}

		add(mapping, fm, req, rep);
		// req.setAttribute("success", fm);
		req.setAttribute(Env.DATA_NAME, message);
		return mapping.findForward("add");
	}

	/**
	 * 准备修改记录
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward modify(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TWorderForm fm = (TWorderForm) form;
		try {
			java.lang.String key = fm.getId();
			TWorder rf = (TWorder) cbiz.getDao().myGet(TWorder.class, key);
			if (rf == null) {
				req.setAttribute(Env.DATA_NAME, "读取数据错误");
				return mapping.findForward("error");
			}
			req.setAttribute(Env.DATA_NAME, rf);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "读取数据错误", e, mapping, req);
		}
		req.setAttribute("statuslist", BeanUtil.startWith("TWorder-status"));
		req.setAttribute("levellist", BeanUtil.startWith("TWorder-level"));
		req.setAttribute("createSourcelist", BeanUtil.startWith("TWorder-createSource"));
		return mapping.findForward("modify");
	}

	/**
	 * 执行记录修改
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doModify(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TWorderForm fm = (TWorderForm) form;
		Object obj = null;
		try {
			obj = cbiz.modify(req, fm, null);
		} catch (MyException e) {
			LogUtil.e(this.clazz, "修改数据出现异常", e);
		}
		log.info("修改记录结果：" + obj);
		if (obj == null || !(obj instanceof TWorder)) {
			req.setAttribute(Env.DATA_NAME, "操作失败，" + obj);
			return mapping.findForward("error");
		}
		req.setAttribute(Env.DATA_NAME, "记录修改成功");
		return mapping.findForward("success");
	}

	/**
	 * 查询记录详细信息
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward detail(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {

		TWorderForm fm = (TWorderForm) form;
		IBaseDao dao = cbiz.getDao();
		try {
			java.lang.String key = fm.getId();
			TWorder pojo = (TWorder) dao.myGet(TWorder.class, key);
			if (pojo == null) {
				req.setAttribute(Env.DATA_NAME, "查看的信息不存，有疑问请联系管理员");
				return mapping.findForward("error");
			}
			req.setAttribute(Env.DATA_NAME, pojo);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "操作失败，未能读取相关信息的详细资料", e, mapping, req);
		}
		req.setAttribute("statuslist", BeanUtil.startWith("TWorder-status"));
		req.setAttribute("levellist", BeanUtil.startWith("TWorder-level"));
		req.setAttribute("createSourcelist", BeanUtil.startWith("TWorder-createSource"));

		return mapping.findForward("detail");
	}

	/**
	 * 执行删除操作
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doDelete(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TWorderForm fm = (TWorderForm) form;
		List res = null;
		try {
			res = cbiz.delete(req, fm, null);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "操作失败，执行删除记录失败", null, mapping, req);
		}
		if (res == null || !(res instanceof List)) {
			return LogUtil.e(this.clazz, "操作失败，执行删除记录失败", null, mapping, req);
		} else {
			req.setAttribute(Env.DATA_NAME, "操作完成，删除记录数量：" + res.size());
			return mapping.findForward("success");
		}
	}

	/**
	 * 导出数据
	 * 
	 * @param mapping
	 * @param form
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doExport(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {

		try {
			TWorderHql hql0 = new TWorderHql();
			List list = this.cbiz.getDao().myList(hql0.getHql(req, form), hql0.getParaValue(req, form));
			if (list == null || list.size() < 1) {
				req.setAttribute(Env.DATA_NAME, "本次查询没有数据，所以不做导出");
				return mapping.findForward("success");
			}

			ExportTemplate template = new ExportTemplate() {
				private static final long serialVersionUID = 1L;

				@Override
				public void setRow(DataRow row, Object obj) {
					Object[] arr = (Object[]) obj;
					TWorder pojo = (TWorder) arr[0];
					TCrm crm = (TCrm) arr[1];
					row.add(CU.valueOf(pojo.getSn()));
					row.add(CU.valueOf(pojo.getStatus()));
					row.add(CU.valueOf(pojo.getLevel()));
					row.add(CU.valueOf(crm.getName()));
					row.add(CU.valueOf(pojo.getFagent()));
					row.add(CU.valueOf(pojo.getToAgent()));
					row.add(CU.valueOf(pojo.getSubject()));
					row.add(CU.valueOf(pojo.getContext()));
					row.add(CU.valueOf(pojo.getCreateSource()));
					row.add(CU.valueOf(pojo.getCreateObject()));
					row.add(DT.getYMDHMS(pojo.getCreateTime()));
				}
			};
			String root3path3file = AgentEnv.EXPORT_PATH + CU.getSerial(".xls");
			template.setRoot3path3file(root3path3file);
			template.setContentTitle(new String[] { "工单号", "状态", "等级", "访客", "第一位坐席", "受理坐席", "主题", "工单内容", "创建源", "创建对象", "创建时间" });

			IDataPort port = new JxlPort();
			template.setDataList(list);
			port.export(template);

			IFileLoad fl = new FileLoad();
			fl.download(req, rep, this.servlet.getServletConfig(), root3path3file);

			IFileProcessor fp = new FileProcessor();
			fp.delete(root3path3file);

		} catch (MyException e) {
			return LogUtil.e(this.clazz, "操作出现错误", e, mapping, req);
		}

		return null;
	}

	/**
	 * 准备导入
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward importer(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		return mapping.findForward("importer");
	}

	/**
	 * 导出数据
	 * 
	 * @param mapping
	 * @param form
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doImporter(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		IFileLoad fl = new FileLoad();
		List<String> importerfiles;
		try {
			importerfiles = fl.uploadToPath(form, "d:/web/file/", true);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "文件上传失败，不能进行导入", e, mapping, req);
		}

		final List statuslist = BeanUtil.startWith("TWorder-status");
		final List levellist = BeanUtil.startWith("TWorder-level");
		final LogonSession ls = new LogonSession(req);
		final HttpServletRequest req0 = req;
		ImportTemplate template = new ImportTemplate() {
			@Override
			public Object setObject(DataRow row, Object other) throws MyException {
				TWorder pojo = new TWorder();
				pojo.setOrg(ConversionUtils.convert(ls.getAttribute("attribute.org"), String.class));
				pojo.setSn(RedisManager.getInstance().getOrderNo(String.valueOf(ls.getAttribute("attribute.pid"))));
				pojo.setStatus(ConversionUtils.convert(BeanUtil.getFirstValueFromObject(row.get(1), statuslist), String.class));
				pojo.setLevel(ConversionUtils.convert(BeanUtil.getFirstValueFromObject(row.get(2), levellist), Integer.class));
				pojo.setCrm(row.get(3));
				pojo.setFagent(row.get(4));
				pojo.setToAgent(row.get(5));
				pojo.setSubject(row.get(6));
				pojo.setContext(row.get(7));
				pojo.setCreateSource(AgentConstant.CREATE_SOURCE.IMP.name());
				pojo.setCreateObject(row.get(8));
				pojo.setCreateTime(System.currentTimeMillis());
				pojo.setTag1(row.get(9));
				pojo.setTag2(row.get(10));
				pojo.setTag3(row.get(11));
				pojo.setTag4(row.get(12));
				pojo.setExtend1(row.get(13));
				pojo.setExtend2(row.get(14));
				pojo.setExtend3(row.get(15));
				pojo.setExtend4(row.get(16));
				pojo.setExtend5(row.get(17));
				pojo.setExtend6(row.get(18));
				pojo.setExtend7(row.get(19));
				pojo.setExtend8(row.get(20));
				pojo.setExtend9(row.get(21));
				pojo.setExtend10(row.get(22));
				return pojo;
			}
		};
		template.setErrorInputAllowed(false);
		template.setErrorInsertAllowed(false);
		template.setRoot3path3file(importerfiles.get(0));
		template.setBaseDao(cbiz.getDao());
		template.setStart(1);
		IDataPort port = new JxlPort();
		try {
			port.importer(template);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "数据导入失败", e, mapping, req);
		}
		int success = template.getSuccess();
		String show = "数据已经成功导入，导入数量有：" + success;
		int error = template.getError();
		if (error > 0)
			show = show + "，有" + error + "条记录不能正常导入";
		req.setAttribute(Env.DATA_NAME, show);

		return mapping.findForward("success");
	}

	/**
	 * 下载模板
	 * 
	 * @param mapping
	 * @param form
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward template(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		String path = "d:/web/file/";
		try {
			if (!FU.isExist(path + "/template.xls", false)) {
				ExportTemplate template = new ExportTemplate() {
					private static final long serialVersionUID = 1L;

					@Override
					public void setRow(DataRow row, Object obj) {
					}
				};
				template.setRoot3path3file(path + "/template.xls");
				template.setContentTitle(new String[] { " pid", " 工单号", " 状态", " 等级", " 访客", " 第一位坐席", " 受理坐席", " 主题", " 工单内容", " 创建源", " 创建对象",
						" tag1", " tag2", " tag3", " tag4", " extend1", " extend2", " extend3", " extend4", " extend5", " extend6", " extend7",
						" extend8", " extend9", " extend10", });
				template.setDataList(new ArrayList());
				IDataPort port = new JxlPort();
				port.export(template);
			}
			IFileLoad fl = new FileLoad();
			fl.download(req, rep, this.servlet.getServletConfig(), path + "/template.xls");
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "获取模板失败", e, mapping, req);
		}
		return null;
	}

	public void setCbiz(AbstractBiz cbiz) {
		this.cbiz = cbiz;
	}

	public void setPbiz(IPaginationBiz pbiz) {
		this.pbiz = pbiz;
	}
}
